package cn.lixin.hrm.config;

import cn.lixin.hrm.MyUserDetailsService;
import cn.lixin.hrm.filter.SmsAuthenticationFilter;
import cn.lixin.hrm.filter.SmsAuthenticationProvider;
import cn.lixin.hrm.handler.MyAuthenticationFailHandler;
import cn.lixin.hrm.handler.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity  //开启Security
public class SmsAuthConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private MyUserDetailsService myUserDetailsService ;

    @Autowired
    private MyAuthenticationFailHandler myAuthenticationFailureHandler;

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Override
    public  void configure(HttpSecurity http) throws Exception {

        //短信验证码登录=========================================================================================start
        //短信认证Filter
        SmsAuthenticationFilter smsAuthenticationFilter = new SmsAuthenticationFilter();
        smsAuthenticationFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        smsAuthenticationFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);

        smsAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        //短信认证provider
        SmsAuthenticationProvider smsDaoAuthenticationProvider = new SmsAuthenticationProvider();
        smsDaoAuthenticationProvider.setUserDetailService(myUserDetailsService);


        //添加短信认证provider
        http.authenticationProvider(smsDaoAuthenticationProvider);
        //添加短信认证filter
        http.addFilterBefore(smsAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        //短信验证码登录=========================================================================================end
    }
}